<?php

class DefaultController extends MyUserController
{
    public $modelName = '';
        public function accessRules(){
            return array(
                array('allow',
                    'users'=>array('*'),
                ),
                array('allow',
                    'actions'=>array('admin'),
                    'expression' => 'Yii::app()->user->getState("isAdmin")',
                ),
            );
        }
        
        /**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
            'fileUploaderConnector' => "ext.ezzeelfinder.ElFinderConnectorAction",
		);
	}
        
	public function actionIndex()
	{
		//$this->render('index');
            echo 'qeqweqweqw';
	}
	
	public function actionRegister(){
            $return = array('error' => '', 'status' => '', 'data' => '');
            $model_name = 'User';
            $model = new $model_name;
            $model->scenario = 'api';
            if (isset($_REQUEST['username']) && isset($_REQUEST['email']) && isset($_REQUEST['password']))
            {
                //$model->attributes=$_REQUEST[$model_name];
                $model->attributes = array('username' => $_REQUEST['username'], 
                                           'password' => $_REQUEST['password'],
                                           'email' => $_REQUEST['email']);
                if($model->validate()){
                    $model->setPassword();
                    $model->setStatus();
                    $model->save(false);
                    
                    $login_model=new LoginForm;
                    $login_model->attributes = array('username' => $_REQUEST['username'], 'password' => $_REQUEST['password']);
                    if($login_model->login()){
                        $token=new Tokens;
                        //
                        $id = Yii::app()->user->getId();
                        $token->deleteUserTokens($id);
                        $t = $token->generateToken();
                        $token->setIsNewRecord(true);
                        $token->id_user = $id;
                        $token->token = $t;
                        //$token->life_time = time();
                        $token->save(false);
                        //echo 'id:'.$model->i;
                        $return['status'] = 200; 
                        $return['data'] = array('token' => $t);
                    } else {
                        $return['status'] = 401; 
                        $return['error'] = $login_model->getErrors();
                    }
                } else {
                    if ($model->isUserExist($_REQUEST['username'], $_REQUEST['email'])){
                        $return['status'] = 409; 
                    } else {
                        $return['status'] = 401; 
                    }
                    $return['error'] = $model->getErrors();
                }
            }else {
                    $return['status'] = 401; 
                    $return['error'] = 'auth fail';
            }
            echo json_encode($return);
        }
	
	public function actionMarkFilesReaded()
	{
	    $return = array('error' => '', 'status' => '', 'data' => '');
	    if (isset($_REQUEST['token']) )
	    {
		$token=new Tokens;
		$userId = $token->getUserByToken($_REQUEST['token']);
		if ($userId)
		{
		    $files = new Files;
		    $files->markFileReaded($userId);
		    $return['status'] = 200;
		} 
		else 
		{
			$return['error'] = 'Invalid token';
			$return['status'] = 401;
		}
	    }
	    else
	    {
		$return['error'] = 'Invalid token';
		$return['status'] = 401;
	    }
	    echo json_encode($return);
	}
        
        public function actionGetToken(){
		$return = array('error' => '', 'status' => '', 'data' => '');
		if (isset($_REQUEST['username']) && isset($_REQUEST['password'])){
			$model=new LoginForm;
			
                        $model->attributes = array('username' => $_REQUEST['username'], 'password' => $_REQUEST['password']);
			if($model->validate() && $model->login()){
                            $token=new Tokens;
                            //
                            $id = Yii::app()->user->getId();
                            $token->deleteUserTokens($id);
                            $t = $token->generateToken();
                            $token->setIsNewRecord(true);
                            $token->id_user = $id;
                            $token->token = $t;
                            //$token->life_time = time();
                            $token->save(false);
                            //echo 'id:'.$model->i;
                            $return['status'] = 200; 
                            $return['data'] = array('token' => $t);
			} else {
                            $return['status'] = 401; 
                            $return['error'] = $model->getErrors();
                        }
                        
		} else {
                        $return['status'] = 401; 
			$return['error'] = 'auth fail';
		}
		
		echo json_encode($return);
	}
	
	public function actionGetNewFilesList()
    {
		$return = array('error' => '', 'status' => '', 'data' => '');
		if (isset($_REQUEST['token']) )
		{
			$token=new Tokens;
			$userId = $token->getUserByToken($_REQUEST['token']);
			if ($userId)
			{
			$files = new Files;
			$list = $files->getUserFiles($userId, true);
			if (!empty($list))
			{
				$return['data'] = $list;
				$return['status'] = 200; 
			}
			else
			{
				$return['error'] = 'Empty file list';
				$return['status'] = 204;
			}
			} 
			else 
			{
				$return['error'] = 'Invalid token';
				$return['status'] = 401;
			}
		}
		else
		{
			$return['error'] = 'Invalid token';
			$return['status'] = 401;
		}
		echo json_encode($return);
    }
	
	public function actionCheckNewFilesCount()
    {
		$return = array('error' => '', 'status' => '', 'data' => '');
		if (isset($_REQUEST['token']) )
		{
			$token=new Tokens;
			$user_id = $token->getUserByToken($_REQUEST['token']);
			if ($user_id)
			{
				$files = new Files;
				$cnt = $files->getNewFilesCount($user_id);
				if (!empty($cnt))
				{
					$return['data'] = array(
					'count' => $cnt,
					'date' => $files->getLastFileDate($user_id)
					);
					$return['status'] = 200; 
				}
				else
				{
					$return['error'] = '';
					$return['status'] = 204;
				}
			} 
			else 
			{
				$return['error'] = 'Invalid token';
				$return['status'] = 401;
			}
		}
		else
		{
			$return['error'] = 'Invalid token';
			$return['status'] = 401;
		}
		echo json_encode($return);
    }
        
    public function actionGetList()
    {
	$return = array('error' => '', 'status' => '', 'data' => '');
	if (isset($_REQUEST['token']) )
	{
	    $token=new Tokens;
	    $user_id =  $token->getUserByToken($_REQUEST['token']);
	    if ($user_id)
	    {
		$files = new Files;
		$list = $files->getUserFiles($user_id);
		if (!empty($list))
		{
		    $return['data'] = $list;
		    $return['status'] = 200; 
		}
		else
		{
		    $return['error'] = 'Empty file list';
		    $return['status'] = 204;
		}
	    } 
	    else 
	    {
		$return['error'] = 'Invalid token';
		$return['status'] = 401;
	    }
	} 
	else
	{
	    $return['error'] = 'Invalid token';
	    $return['status'] = 401;
	}
	echo json_encode($return);
    }
    
    public function actionDeleteFile()
    {
	$return = array('error' => '', 'status' => '', 'data' => '');
	if (isset($_REQUEST['token']) && isset($_REQUEST['file_id']))
	{
	    $token=new Tokens;
	    $user_id =  $token->getUserByToken($_REQUEST['token']);
	    if ($user_id)
	    {
		$files = new Files;
		if ($files->isUserFileOwner($user_id, $_REQUEST['file_id']))
		{
		    
		    $this->modelName = 'Files';
		    $this->loadModel($_REQUEST['file_id'])->delete();
		    $return['error'] = tt('File successfully deleted');
		    $return['status'] = 200;
		} 
		else 
		{
		    $return['error'] = 'User is not file owner';
		    $return['status'] = 403;
		}
	    } 
	    else 
	    {
		$return['error'] = 'Invalid token';
		$return['status'] = 401;
	    }
	} 
	else 
	{
	    $return['error'] = 'Invalid params';
	    $return['status'] = 401;
	}
	echo json_encode($return);
    }
}